#!/usr/bin/env python
# -*- coding:utf-8 -*-

#zabbix api 获取history数据
#------草稿----------

import json
import sys
import calendar
import time
from datetime import datetime

from pyzabbix import ZabbixAPI



try:
    zapi = ZabbixAPI("http://monitor.xxx.xxx")
    login = zapi.login("admin","zabbix")
    print "Connected to zabbix API Version %s" % zapi.api_version()
except Exception as e:
    print '\n 登陆zabbix平台出现错误\n'+e
    sys.exit()
#返回templateid
def get_templateid(template_name):
    global zapi
    if not template_name:
        template_name='Template OS Linux'
    for tplid in zapi.template.get(output="shorten",filter={'host':[template_name]}):
        templateid = tplid['templateid']
    return templateid

#---------------------------------------
#返回hostid，hostname
def get_hosts(template_name):
    global zapi
    hosts = {}
    templateid = get_templateid(template_name)
    for h in zapi.host.get(output=["hostid","host"],filter={'templateids':[templateid]}):
        hostid,name = h['hostid'],h['host']
        hosts[hostid] = name
    #print hosts
    return hosts
#---------------------------------------
#返回itemid，hostid
def get_item(template_name,item_key):
    global zapi
    item ={}
    templateid = get_templateid(template_name)
    for it in zapi.item.get(output=["hostid","itemid"],filter={'templateids':[templateid]},search={"key_":item_key}):
        hostid,itemid = it["hostid"],it["itemid"]
        item[hostid] = itemid
    return item
#---------------------------------------
def dict_merge(dict1,dict2,last_key,last_value,last_value2):
    last_info = []
    for k,v in dict1.items():
        if k in dict2:
            last_info.append({last_key:k,last_value:dict2[k],last_value2:v})
        else:
            continue
    return last_info
#---------------------------------------
def get_host_hostname_item(template_name,item_key):
    global zapi
    hosts = get_hosts(template_name)
    item = get_item(template_name,item_key)

    host_hostname_item_info = dict_merge(hosts,item,'hostid','itemid','hostname')
    return host_hostname_item_info
    #list = [
    #    {
    #        hostid:''
    #        itemid:''
    #        hostname:''
    #     }
    #]
#---------------------------------------
def get_history_item(item,time_from,time_till):
    global zapi
    
    history_item_info = {}
    hostid_list = item.keys()
    itemid_list = item.values()
    
    for h in zapi.history.get(output="extend",hostids=hostid_list,itemids=itemid_list,time_from=time_from,time_till=time_till):
        history_item_info[h['itemid']] = h['value']
    history_item_info['timepoint'] = time_from
    return history_item_info
'''
def statistic_handle(history_item_info):
    history_value = history_item_info['value']
    hostname = history_item_info['hostname']
    history_max = max(history_value)
    history_avg = sum(history_value)/len(history_value)
    history_min = min(history_value)
    host_name = 
    #print hosts
'''
def get_host_history_timepoint(host_hostname_item_info,history_item_info):
    host_history_timepoint_info = {}
    host_history_timepoint_list = []
    for host_hostname_item in host_hostname_item_info:
        if 'itemid' in host_hostname_item and 'itemid' in history_item_info:
            host_history_timepoint_info['hostid'] = host_hostname_item['hostid']
            host_history_timepoint_info['hostname'] = host_hostname_item['hostname']
            host_history_timepoint_info['value'] = history_item_info['value']
            host_history_timepoint_info['timepoint'] = history_item_info['timepoint']
        host_history_timepoint_list.append(host_history_timepoint_info)
    return host_history_timepoint_list


time_till = time.mktime(datetime.now().timetuple())
time_from = time_till - 60 * 4  # 4 hours
#h_info = get_host_info('Template OS Linux','CheLaiLe.check.cpu.usage')
item = get_item('','CheLaiLe.check.cpu.usage')
history = get_history_item(item,time_from,time_till)
print history
'''
def statistic_handle(history_info_list):
    for history_invaluefo in history_info_list:
        history_value = history_info['value']
        hostname = history_info['hostname']
        history_max = max(history_value)
        history_avg = sum(history_value)/len(history_value)
        history_min = min(history_value)
        host_name = 
        #print hosts

    
    #print json.dumps({"data": h_list })

    #    print history
zapi

根据groupname获取groupid
根据groupid获取所属hostid
根据hostid、itemname获取itemid
根据itemid、开始时间、结束时间获取系统负载trends、history数据
    itemid：cpu us、sys
生成excel报表：
    各服务器平均负载、最高负载
    平均负载占比、最高80%负载时间占比
    
    负载10%、20%、50%、80% 区间服务器台数
'''

class ZabbixReport():
    def daily_report(self):
        pass
    def weekly_report(self):
        pass
    def monthly_repport(self):
        pass
    def report_excel(self):
        pass

'''
#-------------------------------------------------------------
#当天日期
today = datetime.date.today()

def custom_time(startTime,endTime):
    customStart = time.mktime(startTime)
    customEnd = time.mktime(endTime)
    return customStart,customEnd

def get_daily():
    dayStart = int(time.mktime(today.timetuple())) #由今天日期，取得凌晨unix timestamp
    dayEnd = int(time.time()) #获取当前系统unix timestamp
    return dayStart,dayEnd
    #print dayStart,dayEnd

def get_weekly():
    lastMonday = today
    #取得上一个星期一
    while lastMonday.weekday() != calendar.MONDAY:
        lastMonday -= datetime.date.resolution
    
    weekStart = int(time.mktime(lastMonday.timetuple()))# 获取周一午夜的unix timestamp
    weekEnd = int(time.time())#获取当前系统unix timestamp
    weekofmonth = (today.day+7-1)/7
    return weekStart,weekEnd,weekofmonth
    #print weekStart,weekEnd,weekofmonth

def get_monthly():
    firstDay =  today #当前第一天的日期
    #取得当月第一天的日期
    while firstDay.day != 1:
        firstDay -= datetime.date.resolution
    monthStart = int(time.mktime(firstDay.timetuple())) #当月第一天的unix timestamp
    monthEnd = int(time.time())    #当前时间的unix timestamp
    return monthStart,monthEnd
    #print monthStart,monthEnd

#-------------------------------------------------------------

#if __name__ == '__main__':
#    pass
'''